﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Goodway.Dao.Utility;
using System.Xml.Linq;

namespace ExcelImportComponent.Valider.Implement
{
    public class ValidEnum : IVaild
    {
        #region IVaild 成员

        public List<ExcelImportValidMessage> DoValid(string validColumnName, List<Goodway.Dao.Utility.GoodwayEntity> entities,XElement validSetting,string schemaname)
        {
            if (string.IsNullOrEmpty(validSetting.Attribute("EnumDes").Value)) throw new Exception("枚举验证时 请输入EnumDes");
            if (string.IsNullOrEmpty(validSetting.Attribute("DataSourceKey").Value)) throw new Exception("枚举验证时 请输入DataSourceKey");
            if (string.IsNullOrEmpty(validSetting.Attribute("EnumKey").Value)) throw new Exception("枚举验证时 请输入EnumKey");
            string message = string.Format("不是枚举:{0}", validSetting.Attribute("EnumDes").Value);
            string dataSourceKey = validSetting.Attribute("DataSourceKey").Value;
            string enumKey = validSetting.Attribute("EnumKey").Value;
            IGoodwayEntityProvider provider = GoodwayEntityProviderFactory.GetEntityProvider();
            string strSql = "select * from DicItems where TypeCode='" + enumKey + "'";
            provider.ConStr = dataSourceKey;
            provider.TableName = "DicItems";
            List<GoodwayEntity> list = provider.GetBySql(strSql);
            List<ExcelImportValidMessage> returnValue = new List<ExcelImportValidMessage>();
            for (int i = 0; i < entities.Count; i++)
            {
                GoodwayEntity entity = entities[i];
                if (!string.IsNullOrEmpty(entity[validColumnName]))
                {
                    GoodwayEntity enumEntity = list.FirstOrDefault(p => p["ItemText"] == entity[validColumnName]);
                    if (enumEntity == null)
                    {
                        ExcelImportValidMessage objMessage = new ExcelImportValidMessage(i.ToString(), validColumnName);
                        objMessage.Value = entity[validColumnName];
                        objMessage.ErrorMessage.Add(message);
                        returnValue.Add(objMessage);
                    }
                }
            }
            return returnValue;
        }

        #endregion
    }
}
